package org.goldfish.message_board01.services;


import org.goldfish.message_board01.dao.UserDAO;
import org.goldfish.message_board01.entity.User;

public class UserService extends AbstractService {
    private final UserDAO userDAO;

    public UserService() {
        this.userDAO = new UserDAO();
        addDAO(userDAO);
    }

    /**
     * Validates login credentials.
     *
     * @param name     Username.
     * @param password Password.
     * @return User object if credentials are correct, null otherwise.
     */
    public User login(String name, String password) {
        User user = userDAO.getUserByName(name);
        if (validateUser(name, password)) {
            return user;
        }
        return null;
    }

    /**
     * Registers a new user.
     *
     * @param name     Username.
     * @param password Password.
     * @return true if registration is successful, false otherwise.
     */
    public boolean register(String name, String password) {
        if (userDAO.getUserByName(name) == null) {
            User user = new User(name, password);
            return userDAO.insertUser(user);
        }
        return false;
    }

    public boolean validateUser(String username, String password) {
        User user = userDAO.getUserByName(username);
        return user != null && user.getPassword().equals(password);
    }
    public void destroy() {
        userDAO.destroy();
    }
    public String cesarEncrypt(String text) {
        int[] shifts = {1,2,3,5,4};
        StringBuilder encrypted = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            c += shifts[i % shifts.length];
            encrypted.append(c);
        }
        return encrypted.toString();
    }
}
